<script setup>
import { nextTick, ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';

import { baseURL } from '@/utilities/request';
import { convertToFormData } from '@/utilities/common';
import { uploadCommoditySKUImage, editCommoditySKU } from '@/apis/commodity';

const skuModelRef = ref();
const skuModel = ref({});

let isGiveupWarning = false;
const handleClose = (done) => {
  // 判断是否有部分表单已经赋值了
  var hasValueProps = Object.keys(skuModel.value).filter(
    (key) => skuModel.value[key]
  );
  if (hasValueProps.length > 0) {
    if (!isGiveupWarning) {
      ElMessage.warning('当前的 SKU 未保存，放弃保存请再次点击取消');
      isGiveupWarning = true;
      setTimeout(() => {
        isGiveupWarning = false;
      }, 3000);
      return;
    }
  }

  if (done) {
    done();
  } else {
    dialogVisible.value = false;
  }
};

let skuImageRaw;
const onSKUImageSelectFile = (uploadFile) => {
  skuModel.value.skuImageUrl = URL.createObjectURL(uploadFile.raw);
  skuImageRaw = uploadFile.raw;
};

const rules = ref({
  skuName: [
    {
      required: true,
      message: '请输入 SKU 名称',
      trigger: 'blur'
    },
    {
      pattern: /^\S{2,10}$/,
      message: 'SKU 名称长度需要在2-10个非空字符',
      trigger: 'blur'
    }
  ],
  quantity: [
    {
      required: true,
      message: '请输入数字',
      trigger: 'blur'
    }
  ],
  price: [
    {
      required: true,
      message: '请输入正确的数字',
      trigger: 'blur'
    }
  ]
});

const dialogVisible = ref(false);
const optMode = ref('add');
const targetIndex = ref(-1);
const title = ref('');
const open = (mode, index, model, commodityId) => {
  nextTick(() => {
    skuModelRef.value &&
      skuModelRef.value.clearValidate &&
      skuModelRef.value.clearValidate();
  });

  dialogVisible.value = true;

  optMode.value = mode;
  targetIndex.value = index;
  title.value = model.id ? '编辑 SKU' : '新增 SKU';

  skuModel.value = model;
  skuModel.value.commodityId = commodityId;
};

defineExpose({
  open
});

const emit = defineEmits(['finishEditSKU']);

const onConfirm = async () => {
  await skuModelRef.value.validate();
  if (!skuModel.value.skuImageUrl) {
    ElMessage.error('请选择 SKU 图片');
    return;
  }

  let skuModelCopy = JSON.parse(JSON.stringify(skuModel.value));
  if (optMode.value === 'add') {
    skuModelCopy.skuImageRaw = skuImageRaw;
  } else if (optMode.value === 'edit') {
    if (skuImageRaw) {
      let uploadRes = await uploadCommoditySKUImage(
        convertToFormData({
          name: skuImageRaw.name,
          file: skuImageRaw
        })
      );
      skuModelCopy.skuImageUrl = uploadRes.data;
    } else {
      skuModelCopy.skuImageUrl = skuModelCopy.skuImageUrl.replace(baseURL, '');
    }
    let res = await editCommoditySKU(skuModelCopy);
    ElMessage.success(res.msg);
  }

  emit('finishEditSKU', optMode.value, targetIndex.value, skuModelCopy);
  dialogVisible.value = false;
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="30%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="skuModelRef"
      :model="skuModel"
      :rules="rules"
      label-width="100px"
    >
      <div class="image-uploader-container">
        <el-upload
          class="image-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onSKUImageSelectFile"
        >
          <img
            v-if="skuModel.skuImageUrl"
            :src="skuModel.skuImageUrl"
            class="image"
          />
          <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <el-form-item label="SKU 名称" prop="skuName">
        <el-input v-model="skuModel.skuName"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input-number
          :min="1"
          :precision="0"
          v-model="skuModel.quantity"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
          :min="0.01"
          :precision="2"
          v-model="skuModel.price"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onConfirm">确认</el-button>
        <el-button @click="handleClose()"> 取消 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.image-uploader-container {
  text-align: center;

  .image-uploader {
    padding: 10px;
    .image {
      width: 150px;
      height: 150px;
      display: block;
    }
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    :deep(.el-upload:hover) {
      border-color: var(--el-color-primary);
    }
    :deep(.el-icon.image-uploader-icon) {
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 150px;
      text-align: center;
    }
  }
}
</style>
